package com.ll.blog.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

@Component
@Slf4j
public class Sms {
    @Autowired
    JavaMailSender mailSender;

    public  String getSmsCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int j = random.nextInt(9);
            code.append(j);
        }
        return code.toString();
    }

    public void send(String smsCode,String to) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("shiyi2024@126.com");
        helper.setTo(to);
        // 邮件标题
        helper.setSubject("验证码");
        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(String.format("<p>欢迎注册，你的验证码是: <strong>%s</strong> ,该验证码将在一分钟后过期，如非本人操作，请忽略</p>", smsCode), true);

        // 发送
        mailSender.send(message);
    }
}
